package datastructure;

import java.util.Arrays;
import java.util.Iterator;

public class DynamicList<E> implements Iterable {
    /**
     * 元素列表
     */
    private E[] list;
    /**
     * 列表内元素个数
     */
    private int size;

    public DynamicList() {
        list = (E[]) new Object[5];
    }

    public DynamicList(int length) {
        list = (E[]) new Object[length];
    }

    public E[] getList() {
        return list;
    }

    public int getSize() {
        return size;
    }

    public boolean addElement(E e) {
        if (size >= list.length)
            list = Arrays.copyOf(list, list.length + 5);
        list[size++] = e;
        return true;
    }

    public E getElement(int index) {
        if (index < 0 || index > size - 1)
            return null;
        else
            return list[index];
    }

    public void println() {
        for (int i = 0; i < size; i++)
            System.out.println(list[i]);
    }

    @Override
    public Iterator iterator() {
        return new DynamicListIterator(this);
    }

    private class DynamicListIterator<E> implements Iterator<E> {
        private DynamicList list;
        private int current;

        public DynamicListIterator(DynamicList list) {
            this.list = list;
        }

        @Override
        public boolean hasNext() {
            return current < list.getSize();
        }

        @Override
        public E next() {
            return (E) list.getElement(current++);
        }
    }
}


